<template>
	<view class="sick-apply-container">
		<!-- 渐变颜色背景 -->
		<view class="header-bg">假条申请</view>
		<view class="apply-content">
			<view class="apply-name">
				<text class="apply-title">申请人 :</text>
				<input class="item-name" placeholder="请输入申请人名字" v-model="studentapplyInfo.studentName"></input>
			</view>
			<view class="apply-teacher">
				<text class="apply-title">辅导员 :</text>
				<input class="item-name" placeholder="请输入辅导员名字" v-model="studentapplyInfo.teacherName"></input>
			</view>
			<view class="apply-class">
				<text class="apply-title">班级 :</text>
				<input class="item-name" placeholder="请输入班级名称" v-model="studentapplyInfo.className"></input>
			</view>
			<view class="apply-timestart">
				<text class="apply-title">请假开始时间 :</text>
				<view class="example-body">
					<uni-datetime-picker type="datetime" v-model="studentapplyInfo.startTime" @change=" e => studentapplyInfo.startTime = e" />
				</view>
			</view>
			<view class="apply-timeend">
				<text class="apply-title">请假结束时间 :</text>
				<view class="example-body">
					<uni-datetime-picker position="top" type="datetime" v-model="studentapplyInfo.endTime" @change=" e => studentapplyInfo.endTime = e"/>
				</view>
			</view>
			<view class="apply-reason">
				<text class="apply-title">请假原因 :</text>
				<textarea class="reason-input" placeholder="请输入请假原因" v-model="studentapplyInfo.message"></textarea>
			</view>
		</view>
		<wButton
		     text='提交申请'
			 :bgColor="isgetapplyInfo ? '#1890FF' : ''"
			 @click="apply"
		>
		</wButton>
		
		<!-- 底部导航栏 -->
		<view class="tab-bar">
		  <view 
		    class="tab-item" 
		    :class="{active: currentTab === 0}" 
		    @click="switchTab(0)"
		  >
		    <text class="cuIcon cuIcon-home"></text>
		    <text class="tab-text">首页</text> 
		  </view>
		  
		  <view 
		    class="tab-item" 
		    :class="{active: currentTab === 1}" 
		    @click="switchTab(1)"
		  >
		    <text class="cuIcon cuIcon-form"></text>
		    <text class="tab-text">申请</text>
		  </view>
		  
		  <view 
		    class="tab-item" 
		    :class="{active: currentTab === 2}" 
		    @click="switchTab(2)"
		  >
		    <text class="cuIcon cuIcon-message"></text>
		    <text class="tab-text">消息</text>
		  </view>
		  
		  <view 
		    class="tab-item" 
		    :class="{active: currentTab === 3}" 
		    @click="switchTab(3)"
		  >
		    <text class="cuIcon cuIcon-my"></text>
		    <text class="tab-text">我的</text>
		  </view>
		</view>
	</view>
</template>

<script>
	import wButton from '../../components/watch-login/watch-button.vue'
	import { studentSickApply } from '../../api/sick'
	export default {
		data() {
			return {
				userInfo:{},
				currentTab: 1,
				studentapplyInfo:{
                    classId: 0, //?
                    className: "",
                    studentId : "",
                    studentName: "",
                    message: "",
                    applyTime: "",
                    startTime: "",
                    endTime: "",
                    status: 0,
                    teacherId: 0, //?
                    teacherName: ""
                },
				isgetapplyInfo:false,
			}
		},
		components:{wButton},
		onShow() {
			this.studentapplyInfo = {
				classId: 0, 
				className: "",
				studentId : "",
				studentName: "",
				message: "",
				applyTime: "",
				startTime: "",
				endTime: "",
				status: 0,
				teacherId: 0, 
				teacherName: ""
			}
			this.checkLoginStatus()
			this.studentapplyInfo.studentName = this.userInfo.name
			this.studentapplyInfo.studentId = this.userInfo.studentId
		},
		methods:{
			/**
			 * 模拟学生请假申请API（基于数据库结构）
			 */
			mockStudentSickapply (applyInfo) {
			  return new Promise((resolve) => {
			    // 模拟网络延迟
			    setTimeout(() => {
			      // 从本地存储获取用户信息
			      const userInfo = uni.getStorageSync('userInfo');
			      
			      if (!userInfo) {
			        resolve({
			          code: 401,
			          message: '用户未登录',
			          data: null
			        });
			        return;
			      }
			      
			      // 验证必填字段
			      if (!applyInfo.className || !applyInfo.studentName || !applyInfo.message || 
			          !applyInfo.startTime || !applyInfo.endTime || !applyInfo.teacherName) {
			        resolve({
			          code: 400,
			          message: '请填写完整的申请信息',
			          data: null
			        });
			        return;
			      }
			      
			      // 验证时间逻辑
			      if (new Date(applyInfo.endTime) <= new Date(applyInfo.startTime)) {
			        resolve({
			          code: 400,
			          message: '结束时间必须晚于开始时间',
			          data: null
			        });
			        return;
			      }
			      
			      // 模拟数据库中的请假记录
			      const sickRecord = {
			        id: Math.floor(Math.random() * 10000), // 模拟自增ID
			        student_id: userInfo.id || 2023030102052, // 从用户信息获取学生ID
			        student_name: applyInfo.studentName,
			        status: 0, // 0-待批 1-批准 2-驳回
			        apply_time: applyInfo.applyTime || new Date().toISOString(),
			        start_time: applyInfo.startTime,
			        end_time: applyInfo.endTime,
			        message: applyInfo.message,
			        teacher_id: 123, // 模拟辅导员ID
			        teacher_name: applyInfo.teacherName,
			        class_id: 12345678, // 模拟班级ID
			        class_name: applyInfo.className
			      };
			      
			      // 模拟成功响应
			      resolve({
			        code: 200,
			        message: '请假申请提交成功',
			        data: sickRecord
			      });
			      
			    }, 800); // 800毫秒延迟模拟网络请求
			  });
			},
			
			// 检查登录状态
			checkLoginStatus() {
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.redirectTo({ url: '/pages/login/login' })
					return
				}
				this.userInfo = {
					name: userInfo.name,
					studentId: userInfo.id || 'S202300001',
					role: userInfo.roleName
			    }
			},
			
			//校验
			validateInputs() {
				const { studentName, teacherName, className, message, startTime, endTime} = this.studentapplyInfo;
           
                // 检查姓名是否只包含中文或字母
                if (!/^[\u4e00-\u9fa5a-zA-Z]+$/.test(studentName)) {
					uni.showToast({ title: '姓名只能包含中文或字母', icon: 'none', duration: 2000 });
					return false;
                }
           
                // 检查班级格式（示例：允许数字、字母、中文和短横线）
				if (!/^[\u4e00-\u9fa5a-zA-Z0-9-]+$/.test(className)) {
					uni.showToast({ title: '班级格式不正确', icon: 'none', duration: 2000 });
					return false;
                }
           
                // 检查时间是否合理
			    if (new Date(endTime) <= new Date(startTime)) {
				   uni.showToast({ title: '结束时间必须晚于开始时间', icon: 'none', duration: 2000 });
				   return false;
				}
				
				// 检查申请理由是否为空
				if (message.trim()==='') {
				   uni.showToast({ title: '申请理由不能为空', icon: 'none', duration: 2000 });
				   return false;
				}
           
                return true; // 校验通过
             },
			
			async apply(){
				if(!this.isgetapplyInfo) {
					uni.showToast({ title: '申请信息未填写完整', icon: 'none' ,duration:2000});
					return false;
				} 
				if(! this.validateInputs()) return 
	
				const dayjs = require("dayjs")
				const nowapplyTime=new Date()
				this.studentapplyInfo.applyTime = dayjs(nowapplyTime).format('YYYY-MM-DD HH:mm:ss')
				
				console.log(this.studentapplyInfo)
				
				uni.showLoading({ title:'提交申请中...' })
				try{
					const res = await this.mockStudentSickapply(this.studentapplyInfo)
					// const res = await studentSickApply(this.studentapplyInfo)
					if(res.code===200){
						uni.showToast({
							title:res.message || '申请成功',
							icon:'none',
							duration:2000
						})
					}
				}catch(err){
					uni.showToast({
						title:err.message || '申请失败',
						icon:'none',
						duration:2000
					})
				}finally{
					uni.hideLoading()
					this.studentapplyInfo = {
                      classId: 0,
                      className: "",
                      studentId : "",
                      studentName: "",
                      message: "",
                      applyTime: "",
                      startTime: "",
                      endTime: "",
                      status: 0,
                      teacherId: 0, 
                      teacherName: ""
                    }
					this.studentapplyInfo.studentName = this.userInfo.name
				}
			},
			
			switchTab(index) {
			      const routes = [
			        '/pages/student/student',
			        '/pages/application/list',
			        '/pages/notification/list',
			        '/pages/user/profile'
			      ];
			      if (index >= routes.length) {
			        uni.showToast({
			          title: '功能正在开发中',
			          icon: 'none'
			        });
			        return;
			      }
			      uni.navigateTo({ 
			            url: routes[index],
			            success: () => {
			              console.log('路由跳转成功:', routes[index]);
			            },
			            fail: (err) => {
			              console.error('路由跳转失败:', err);
			              uni.showToast({
			                title: '页面加载失败',
			                icon: 'none'
			              });
			            }
			          });
			},
		},
		watch: {
		  studentapplyInfo: {
		    deep: true, 
			immediate: true,
		    handler(newVal) {
		      this.isgetapplyInfo = (
		        newVal.className &&
		        newVal.studentName &&
		        newVal.message &&
		        newVal.startTime &&
		        newVal.endTime &&
		        newVal.teacherName
		      );
		    },
		  },
		}
	}
</script>

<style>
	@import url("./css/studentSickapply.css");
	@import url("../../components/watch-login/css/icon.css");
</style>